package com.bh.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.base.domain.BhTimeLiness;
import com.bh.base.service.IBhTimeLinessService;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.basemapper.UpdateBatchWrapper;
import com.bh.common.constant.*;
import com.bh.common.core.domain.entity.SysCustomerUser;
import com.bh.common.core.domain.entity.SysUser;
import com.bh.common.enums.OrderStatus;
import com.bh.common.enums.YesOrNo;
import com.bh.common.exception.MessageException;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.*;
import com.bh.common.utils.address.LocalDataAddressDataLoader;
import com.bh.common.utils.address.SmartParse;
import com.bh.common.utils.address.domain.AddressInfo;
import com.bh.common.utils.bean.BeanUtils;
import com.bh.common.utils.bean.BeanValidators;
import com.bh.common.utils.poi.ExcelUtil;
import com.bh.common.utils.spring.SpringUtils;
import com.bh.extend.domain.*;
import com.bh.extend.mapper.JcOrderBarcodeMapper;
import com.bh.extend.service.*;
import com.bh.fee.domain.JcFeeType;
import com.bh.fee.service.IJcFeeTypeService;
import com.bh.framework.web.service.PermissionService;
import com.bh.kysys.domain.JcSysOrganization;
import com.bh.kysys.domain.JcZone;
import com.bh.kysys.service.IJcSysOrganizationService;
import com.bh.kysys.service.IJcZoneService;
import com.bh.ledger.domain.JcLedgerDetail;
import com.bh.ledger.domain.JcVerificationZb;
import com.bh.ledger.mapper.JcLedgerDetailMapper;
import com.bh.ledger.service.IJcLedgerDetailService;
import com.bh.ledger.service.IJcVerificationZbService;
import com.bh.order.convert.JcLedConvert;
import com.bh.order.convert.JcLedProductConvert;
import com.bh.order.convert.JcLedReceivingPartyConvert;
import com.bh.order.convert.JcOrderConvert;
import com.bh.order.domain.*;
import com.bh.order.dto.JcOrderQueryDto;
import com.bh.order.mapper.*;
import com.bh.order.service.*;
import com.bh.order.vo.*;
import com.bh.system.service.ISysCustomerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author slx
 * @date 2023-04-22
 */

@Service
public class JcOrderServiceImpl extends ServiceImpl<JcOrderMapper, JcOrder> implements IJcOrderService {
    public static final String CODE_ONE = "-1";
    @Autowired
    private JcOrderMapper jcOrderMapper;
    @Autowired
    private JcOrderBarcodeMapper jcOrderBarcodeMapper;
    @Autowired
    private JcOrderReceivingPartyMapper jcOrderReceivingpartyMapper;
    @Autowired
    private JcOrderProductMapper jcOrderProductMapper;
    @Autowired
    private JcLedgerDetailMapper jcLedgerDetailMapper;
    @Autowired
    private JcOrderTrackMapper jcOrderTrackMapper;
    @Autowired
    private IJcOrderTrackService jcOrderTrackService;
    @Autowired
    private IJcOrderReceivingPartyService jcOrderReceivingPartyService;
    @Autowired
    private IJcOrderProductService jcOrderProductService;
    @Autowired
    private IJcCustomerService jcCustomerService;
    @Autowired
    private IJcReceivingPartyService jcReceivingPartyService;
    @Autowired
    private IJcLedService jcLedService;
    @Autowired
    private IJcLedgerDetailService jcLedgerDetailService;
    @Autowired
    private JcZoneStoreroomMapper jcZoneStoreroomMapper;
    @Autowired
    private JcServerZoneMapper jcServerZoneMapper;
    @Autowired
    private IJcServerZoneService jcServerZoneService;
    @Autowired
    private IJcSysOrganizationService sysOrganizationService;
    @Autowired
    private IJcZoneStoreroomService zoneStoreroomService;
    @Autowired
    private IJcInOrOutRecordService jcInOrOutRecordService;
    @Autowired
    private IJcOrderBackService jcOrderBackService;
    @Autowired
    private IJcVerificationZbService jcVerificationZbService;
    @Autowired
    private IJcZoneService jcZoneService;
    @Resource
    private RedisCodeUtil redisCodeUtil;
    @Autowired
    private IBhTimeLinessService jcTimeLinessService;
    @Autowired
    private ISysCustomerUserService sysCustomerUserService;
    @Autowired
    private IJcOrderHandleService jcOrderHandleService;
    @Autowired
    private IJcFeeTypeService jcFeeTypeService;
    @Autowired
    private IJcVerificationZbService verificationZbService;
    @Autowired
    private IJcAbnormalService jcAbnormalService;
    @Autowired
    private IJcAbnormalDetailService jcAbnormalDetailService;
    @Autowired
    protected PermissionService permissionService;
    @Autowired
    protected Validator validator;
    @Autowired
    private JcOrderConvert jcOrderConvert;
    @Autowired
    private JcLedConvert jcLedConvert;
    @Autowired
    private JcLedReceivingPartyConvert jcLedReceivingPartyConvert;
    @Autowired
    private JcLedProductConvert jcLedProductConvert;
    @Autowired
    private IJcCustomerPriceService jcCustomerPriceService;

    private final SmartParse smartParse = new SmartParse(new LocalDataAddressDataLoader());

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @DataDictClass
    @Override
    public JcOrder selectJcOrderById(Long id) {
        JcOrder order = jcOrderMapper.selectById(id);
        if (order == null) {
            order = jcOrderMapper.selectJcOrderByCode(String.valueOf(id));
        }
        if (order == null) {
            JcOrderBarcode barcode = jcOrderBarcodeMapper.selectJcOrderBarcodeByCode(String.valueOf(id));
            order = jcOrderMapper.selectById(barcode.getOrderId());
        }
        if (order == null && Objects.equals(SecurityUtils.getSysUser().getUserType(), "01")) {
            SysCustomerUser customerUser = sysCustomerUserService.selectUserById(SecurityUtils.getUserId());
            order = jcOrderMapper.selectJcOrderByRelateBill2(String.valueOf(id), customerUser.getCustomerId());
        }
        if (order == null) {
            return null;
        }
        if (StringUtils.isNotBlank(order.getJcCustomerId())) {
            JcCustomer customer = jcCustomerService.selectJcCustomerById(order.getJcCustomerId());
            order.setCustomerName(customer.getName());
        }
        List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(order.getId());
        if (orderReceivingParties != null && orderReceivingParties.size() > 0) {
            order.setOrderReceivingParties(orderReceivingParties);
            if (orderReceivingParties.size() == 2) {
                for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                    if (orderReceivingParty.getType() == 0) {
                        order.setSender(orderReceivingParty);
                    } else {
                        order.setReceiver(orderReceivingParty);
                    }
                }
            }
        }
        List<JcOrderProduct> orderProducts = jcOrderProductService.selectJcOrderProductListByOrderId(order.getId());
        if (orderProducts != null && !orderProducts.isEmpty()) {
            order.setOrderProducts(orderProducts);
        }
        // 需要财务角色的权限才能看到
        if (permissionService.hasRole("financial") || permissionService.hasRole("admin")) {
            List<JcLedgerDetail> jcLedgerDetails = jcLedgerDetailService.selectJcLedgerDetailListByOrderId(order.getId());
            if (jcLedgerDetails != null && !jcLedgerDetails.isEmpty()) {
                order.setLedgerDetails(jcLedgerDetails);
            }
        }
        JcSysOrganization formOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcOrganizationId());
        if (formOrganization != null) {
            order.setFromOrganization(formOrganization);
        }
        JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcToOrganizationId());
        if (toOrganization != null) {
            order.setToOrganization(toOrganization);
        }
        JcZoneStoreroom zoneStoreroom = zoneStoreroomService.selectJcZoneStoreroomById(order.getJcZoneStoreroomId());
        if (zoneStoreroom != null) {
            order.setZoneStoreroom(zoneStoreroom);
        }

        return order;
    }

    public void handleJcOrder(JcOrder order) {
        if (StringUtils.isNotBlank(order.getJcCustomerId())) {
            JcCustomer customer = jcCustomerService.selectJcCustomerById(order.getJcCustomerId());
            order.setCustomerName(customer.getName());
        }
        List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(order.getId());
        if (orderReceivingParties != null && orderReceivingParties.size() > 0) {
            order.setOrderReceivingParties(orderReceivingParties);
        }
        List<JcOrderProduct> orderProducts = jcOrderProductService.selectJcOrderProductListByOrderId(order.getId());
        if (orderProducts != null && orderProducts.size() > 0) {
            order.setOrderProducts(orderProducts);
        }
        JcSysOrganization formOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcOrganizationId());
        if (formOrganization != null) {
            order.setFromOrganization(formOrganization);
        }
        JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcToOrganizationId());
        if (toOrganization != null) {
            order.setToOrganization(toOrganization);
        }
        JcZoneStoreroom zoneStoreroom = zoneStoreroomService.selectJcZoneStoreroomById(order.getJcZoneStoreroomId());
        if (zoneStoreroom != null) {
            order.setZoneStoreroom(zoneStoreroom);
        }
    }

    @Override
    public JsOrderToAndReceiveVo selectToAndReceiveVoById(Long id) {
        JcOrder order = jcOrderMapper.selectById(id);
        JsOrderToAndReceiveVo toAndReceiveVo = jcOrderConvert.toReceiveVo(order);

        // 地址
        List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(id);
        if (orderReceivingParties != null && orderReceivingParties.size() > 0) {
            for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                if (orderReceivingParty.getType() == 0) {
                    toAndReceiveVo.setFromParties(orderReceivingParty);
                } else {
                    toAndReceiveVo.setToParties(orderReceivingParty);
                }
            }
        }
        List<JcOrderProduct> orderProducts = jcOrderProductService.selectJcOrderProductListByOrderId(id);
        if (orderProducts != null && orderProducts.size() > 0) {
            order.setOrderProducts(orderProducts);
        }
        JcSysOrganization formOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcFromOrganizationId());
        if (formOrganization != null) {
            order.setFromOrganization(formOrganization);
        }
        JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcToOrganizationId());
        if (toOrganization != null) {
            order.setToOrganization(toOrganization);
        }
        //
        return toAndReceiveVo;
    }


    @DataDictClass
    @Override
    public JcOrder selectJcOrderByCode(String code) {
        return jcOrderMapper.selectJcOrderByCode(code);
    }

    /**
     * 查询订单列表
     *
     * @param jcOrder 订单
     * @return 订单
     */
    @DataDictClass
    @Override
    public List<JcOrderRowVo> selectJcOrderList(JcOrderQueryDto jcOrder) {
        List<JcOrder> orders = jcOrderMapper.selectJcOrderList(jcOrder);
        List<JcOrderRowVo> orderRowVos = new ArrayList<>();
        for (JcOrder order : orders) {
            JcOrderRowVo orderRowVo = jcOrderConvert.toRowVo(order);
            if (StringUtils.isNotBlank(order.getJcCustomerId())) {
                JcCustomer customer = jcCustomerService.selectJcCustomerById(order.getJcCustomerId());
                orderRowVo.setCustomerName(customer.getName());
            }
            // 地址
            List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(order.getId());
            orderRowVo.setOrderReceivingParties(orderReceivingParties);
            JcSysOrganization formOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcOrganizationId());
            if (formOrganization != null) {
                orderRowVo.setFromOrganization(formOrganization);
            }
            JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcToOrganizationId());
            if (toOrganization != null) {
                orderRowVo.setToOrganization(toOrganization);
            }
            JcZoneStoreroom zoneStoreroom = zoneStoreroomService.selectJcZoneStoreroomById(order.getJcZoneStoreroomId());
            if (zoneStoreroom != null) {
                orderRowVo.setZoneStoreroom(zoneStoreroom);
            }
        }
        return orderRowVos;
    }

    @Override
    public List<JcOrderVO> selectJcOrderVoList(JcOrderQueryDto jcOrder) {
        return jcOrderMapper.selectJcOrderVoList(jcOrder);
    }

    @Override
    public Map<String, Object> selectJcOrderVoListStatistics(JcOrderQueryDto jcOrder) {
        return jcOrderMapper.selectJcOrderVoListStatistics(jcOrder);
    }

    @Override
    public List<JcOrderCustVO> selectJcOrderCustVoList(JcOrderQueryDto jcOrder) {
        List<JcOrderVO> orderRowVos = jcOrderMapper.selectJcOrderVoList(jcOrder);
        return jcOrderConvert.toCustVoList(orderRowVos);
    }

    @Override
    public List<JcOrderSysApiVO> selectJcOrderSysApiVoList(JcOrderQueryDto jcOrder) {
        List<JcOrderVO> orderRowVos = jcOrderMapper.selectJcOrderVoList(jcOrder);
        List<JcOrderSysApiVO> orderSysApiVos = new ArrayList<>();
        for (JcOrderVO orderRowVo : orderRowVos) {
            JcOrderSysApiVO orderSysApiVO = jcOrderConvert.toSysApiVO(orderRowVo);
            orderSysApiVos.add(orderSysApiVO);
        }
        return orderSysApiVos;
    }

    @Override
    public List<JcOrderVO> selectLedgerDetailList(JcOrderQueryDto jcOrder) {
        return jcOrderMapper.selectLedgerDetailList(jcOrder);
    }


    @DataDictClass
    @Override
    public List<JcOrderRowVo> selectCustJcOrderList(JcOrderQueryDto jcOrder) {
        List<JcOrder> orders = jcOrderMapper.selectJcOrderList(jcOrder);
        List<JcOrderRowVo> orderRowVos = new ArrayList<>();
        for (JcOrder order : orders) {
            JcOrderRowVo orderRowVo = jcOrderConvert.toRowVo(order);
            if (StringUtils.isNotBlank(order.getJcCustomerId())) {
                JcCustomer customer = jcCustomerService.selectJcCustomerById(order.getJcCustomerId());
                orderRowVo.setCustomerName(customer.getName());
            }
            // 地址
            List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(order.getId());
            orderRowVo.setOrderReceivingParties(orderReceivingParties);
            JcSysOrganization formOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcFromOrganizationId());
            if (formOrganization != null) {
                orderRowVo.setFromOrganization(formOrganization);
            }
            JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationById(order.getJcToOrganizationId());
            if (toOrganization != null) {
                orderRowVo.setToOrganization(toOrganization);
            }
            orderRowVos.add(orderRowVo);
        }
        return orderRowVos;
    }


    @Override
    public String importNewOrder(List<JcOrderImportVo> orderList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        // 返回导入提示信息、统计信息（总数、成功数、失败数）
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 将导入不成功的数据导出为excel
        List<JcOrderImportVo> failList = new ArrayList<>();

        for (int i = 1; i <= orderList.size(); i++) {
            JcOrderImportVo importVo = orderList.get(i - 1);
            try {
                BeanValidators.validateWithException(validator, importVo);

                JcOrder order = jcOrderConvert.toDO(importVo);
                order.setCode(redisCodeUtil.getOrderCode());
                order.setJcOrganizationId(SecurityUtils.getOrgId());
                order.setIsTake(0);
                order.setOrderMileage(0D);
                order.setIsConfirm(0);
                order.setSalePerson("李富斌");
                if (StringUtils.isNull(importVo.getTime())) {
                    order.setTime(new Date());
                }
                if (importVo.getBackNumber() != null && importVo.getBackNumber() > 0) {
                    order.setIsBack(1);
                } else {
                    order.setIsBack(0);
                }
                order.setPlanLeaveTime(DateUtils.getSecondDate(order.getTime()));
                order.setPlanArriveTime(DateUtils.getPlanSecondDate(order.getTime()));
                //发货单号
                JcOrder relateBill1Order = jcOrderMapper.selectJcOrderByCode(importVo.getRelateBill1());
                if (relateBill1Order != null) {
                    String message = "发货单号重复，请勿重复录入! ";  // 客户类型与客户名称判断
                    throw new ServiceException(message);
                }

                //客户类型 0：零散 1：合同
                if (importVo.getCustomerType() == 1) {
                    JcCustomer customer = jcCustomerService.selectJcCustomerByName(importVo.getCustomerName());
                    if (customer != null) {
                        if (customer.getDays() > 0) {
                            order.setCustomerIsExceed(Entity.ACTIVE);
                            order.setJcCustomerId(customer.getId());
                            order.setSalePerson(customer.getSalePerson());
                        } else {
                            String message = "客户合同已经过期，请重新录入合同! ";  // 客户类型与客户名称判断
                            throw new ServiceException(message);
                        }
                    } else {
                        String message = "客户名称与客户类型不匹配，请重新录入! ";  // 客户类型与客户名称判断
                        throw new ServiceException(message);
                    }
                }
                //在库位置(先查询是否有大库的存在)
                JcZoneStoreroom jcZoneStoreroom = new JcZoneStoreroom();
                jcZoneStoreroom.setName(importVo.getZoneStoreroomName());
                jcZoneStoreroom.setJcOrganizationId(SecurityUtils.getOrgId());
                List<JcZoneStoreroom> zoneStorerooms = jcZoneStoreroomMapper.selectJcZoneStoreroomList(jcZoneStoreroom);
                if (zoneStorerooms.size() > 0) {
                    order.setJcZoneStoreroomId(zoneStorerooms.get(0).getId());
                } else {
                    // 客户类型与客户名称判断
                    String message = "本平台库存区域为空，请添加库存区域! ";
                    throw new ServiceException(message);
                }
                //出发网点
                JcSysOrganization organization = sysOrganizationService.selectJcSysOrganizationByName(importVo.getJcOrganizationIdName());
                if (organization != null) {
                    order.setJcOrganizationId(organization.getId());
                } else {
                    String message = "没有查找到该出发网点，请添加目的网点! ";
                    throw new ServiceException(message);
                }

                if (StringUtils.isBlank(organization.getAddress())) {
                    String message = "请完善出发网点的地址信息! ";
                    throw new ServiceException(message);
                }
                //出发运点
                JcServerZone startZone = jcServerZoneService.selectJcServerZoneByName(importVo.getJcStartZoneIdName(), organization.getId());
                if (startZone != null) {
                    order.setJcStartZoneId(startZone.getId());
                } else {
                    JcServerZoneVo jcServerZone = new JcServerZoneVo();
                    jcServerZone.setZones(importVo.getJcStartZoneIdName());
                    jcServerZone.setOrgId(organization.getId());

                    Long jcStartZoneId = jcServerZoneService.insertJcServerZoneByAddress(jcServerZone);
                    if (jcStartZoneId == null) {
                        String message = "没有查找到该出发运点，请填写正确的出发运点! ";
                        throw new ServiceException(message);
                    } else {
                        order.setJcStartZoneId(jcStartZoneId);
                    }

                }
                //目的网点
                JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationByName(importVo.getJcToOrganizationIdName());
                if (toOrganization != null) {
                    order.setJcToOrganizationId(toOrganization.getId());
                } else {
                    String message = "没有查找到该目的网点，请添加目的网点! ";

                    throw new ServiceException(message);
                }
                //目的运点
                JcServerZone endZone;
                if (StringUtils.isBlank(importVo.getJcEndZoneIdName())) {
                    AddressInfo addressInfo = smartParse.parseAddressInfo(importVo.getToAddress());
                    if (addressInfo == null || StringUtils.isBlank(addressInfo.getStreetCode())) {
                        String message = "没有查找到该出发运点，请填写正确的出发运点! ";
                        throw new ServiceException(message);
                    } else {
                        importVo.setToStreetCode(addressInfo.getStreetCode());
                        endZone = jcServerZoneMapper.selectJcServerZoneByZoneId(Long.valueOf(addressInfo.getStreetCode()), toOrganization.getId());
                    }
                } else {
                    endZone = jcServerZoneService.selectJcServerZoneByName(importVo.getJcEndZoneIdName(), toOrganization.getId());
                }
                if (endZone != null) {
                    order.setJcEndZoneId(endZone.getId());
                } else if (StringUtils.isNotBlank(importVo.getJcEndZoneIdName())) {
                    JcServerZoneVo jcServerZone = new JcServerZoneVo();
                    jcServerZone.setZones(importVo.getJcEndZoneIdName());
                    jcServerZone.setOrgId(toOrganization.getId());

                    Long jcEndZoneId = jcServerZoneService.insertJcServerZoneByAddress(jcServerZone);
                    if (jcEndZoneId == null) {
                        // 手动添加数据
                        String message = "没有查找到该目的运点，请添加目的运点! ";
                        throw new ServiceException(message);
                    } else {
                        order.setJcEndZoneId(jcEndZoneId);
                    }
                } else {
                    // 手动添加数据
                    String message = "没有查找到该目的运点，请添加目的运点或者地址! ";
                    throw new ServiceException(message);
                }
                //货品处理 先判断之前有没有错误，如果有错误 这不创建订单
                List<JcOrderProduct> orderProducts = new ArrayList<>();
                JcOrderProduct orderProduct = new JcOrderProduct();
                //货品名称
                orderProduct.setName(importVo.getProductName());
                //货品类型
                orderProduct.setType(importVo.getProductType());
                //货品包装
                orderProduct.setPackageType(importVo.getPackageType());
                //货品数量
                orderProduct.setNumber(importVo.getProductNumber());
                //货品重量
                orderProduct.setWeight(importVo.getProductWeight());
                //货品体积
                orderProduct.setVolume(importVo.getProductVolume());
                //货品计重
                BigDecimal zl = importVo.getProductWeight();
                BigDecimal tj = importVo.getProductVolume();
                if (tj != null) {
                    BigDecimal jz;
                    if (zl != null && zl.compareTo(tj.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP)) > 0) {
                        jz = zl;
                    } else {
                        jz = tj.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
                    }
                    orderProduct.setJzWeight(jz);
                }

                orderProduct.setValue(BigDecimal.ZERO);
                orderProducts.add(orderProduct);
                order.setOrderProducts(orderProducts);
                //发货方处理
                List<JcOrderReceivingParty> orderReceivingParties = new ArrayList<>();
                JcOrderReceivingParty from = new JcOrderReceivingParty();
                if (StringUtils.isBlank(organization.getAddress())) {
                    // 手动添加数据
                    String message = "没有查找到该目的运点，请添加目的运点! ";

                    throw new ServiceException(message);
                }
                from.setAddressType(importVo.getFromAddressType());
                from.setContactperson(importVo.getFromContactperson());
                from.setIphone(importVo.getFromIphone());
                from.setName(importVo.getCustomerName());

                from.setAddress(organization.getAddress());
                from.setDetaileAddress(organization.getAddress());
                from.setLtl(organization.getLatitude());

                from.setStatus(Entity.ACTIVE);
                Map<String, String> fromMap = jcZoneService.selectJcZoneByZoneNames(importVo.getJcStartZoneIdName());
                if (StringUtils.isNotBlank(fromMap.get("lastZoneId"))) {
                    from.setJcZoneId(Long.valueOf(fromMap.get("lastZoneId")));
                }
                from.setType(0);
                orderReceivingParties.add(from);
                // 收货方
                JcOrderReceivingParty to = new JcOrderReceivingParty();
                to.setAddress(importVo.getToAddress());
                to.setDetaileAddress(importVo.getToAddress());
                to.setAddressType(importVo.getToAddressType());
                to.setName(importVo.getToCustomerName());
                to.setContactperson(importVo.getToCustomerName());
                to.setIphone(importVo.getToIphone());
                to.setStatus(Entity.ACTIVE);
                Map<String, String> toMap = jcZoneService.selectJcZoneByZoneNames(importVo.getJcEndZoneIdName());
                if (StringUtils.isNotBlank(toMap.get("lastZoneId"))) {
                    to.setJcZoneId(Long.valueOf(toMap.get("lastZoneId")));
                }
                JcReceivingParty toReceivingParty = jcReceivingPartyService.selectJcReceivingpartyListByName(importVo.getToAddress());
                if (toReceivingParty != null && StringUtils.isNotBlank(toReceivingParty.getLtl())) {
                    to.setLtl(toReceivingParty.getLtl());
                } else {
                    to.setLtl(MapUtils.getLonAndLatString(importVo.getToAddress()));
                }
                to.setType(1);
                orderReceivingParties.add(to);

                order.setOrderReceivingParties(orderReceivingParties);
                successNum += SpringUtils.getBean(this.getClass()).saveOrder(order);
                successMsg.append("<br/>" + successNum + "、订单 " + importVo.getRelateBill1() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                failList.add(importVo);
                String msg = "<br/> 您好，第[ " + i + "]行，导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增订单
     *
     * @param jcOrder 订单
     * @return 结果
     */
    public int saveOrder(JcOrder jcOrder) {
        //绑定组织机构(通过客户所属机构来判断)
        SysUser user = SecurityUtils.getSysUser();
        Long jcOrganizationId;
        JcCustomer customer = jcCustomerService.selectJcCustomerById(jcOrder.getJcCustomerId());
        if (StringUtils.isEmpty(jcOrder.getCustomerName()) && customer != null) {
            jcOrder.setCustomerName(customer.getName());
        }
        if (Objects.equals(user.getUserType(), UserConstants.SYSTEM_USER_TYPE)) {
            jcOrganizationId = SecurityUtils.getOrgId();
        } else {
            jcOrganizationId = customer.getJcOrganizationId();
        }
        if (StringUtils.isBlank(jcOrder.getCode())) {
            jcOrder.setCode(redisCodeUtil.getOrderCode());
        }
        if (StringUtils.isEmpty(jcOrder.getId())) {
            jcOrder.setJcOrganizationId(jcOrganizationId);
        }
        if (jcOrder.getJcFromOrganizationId() == null) {
            // 暂时默认出发网点，后期如果变化在进行修改 --TODO
            jcOrder.setJcFromOrganizationId(jcOrganizationId);
        }
        if (jcOrder.getIsBack() == 0) {
            //处理回单份数
            jcOrder.setBackNumber(0);
        }


        jcOrder.setIsTake(0);
        //处理合同是否超期
        if (jcOrder.getCustomer() == null) {
            jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
        } else {
            if (customer.getDays() > 0) {
                jcOrder.setCustomerIsExceed(Entity.ACTIVE);
            } else {
                jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
            }
        }
        //增加路由信息
        BhTimeLiness timeList = jcTimeLinessService.selectJcTimeLinessByOrgs(jcOrder.getJcOrganizationId(), jcOrder.getJcToOrganizationId());
        if (timeList != null) {
            jcOrder.setRouterOrgIds(timeList.getRouterOrgIds());
        } else {
            throw new ServiceException("路线信息不存在，请先添加路线！");
        }
        try {
            //增加路由信息
            jcOrder.setStatus(OrderStatus.ACTIVE.getValue());
            jcOrder.setCreateName(SecurityUtils.getUsername());
            jcOrder.setCreateTime(DateUtils.getNowDate());

            int num = jcOrderMapper.insert(jcOrder); //保存订单单头


            //保存收发货方
            String addressType = "";
            List<JcOrderReceivingParty> orderReceivingParties = jcOrder.getOrderReceivingParties();//获取收发货方
            if (orderReceivingParties == null || orderReceivingParties.size() == 0) {
                // 两种方式
                orderReceivingParties = new ArrayList<>();
                JcOrderReceivingParty sender = jcOrder.getSender();
                sender.setType(0);
                sender.setStatus(Entity.ACTIVE);
                orderReceivingParties.add(sender);
                JcOrderReceivingParty receiver = jcOrder.getReceiver();
                receiver.setType(1);
                receiver.setStatus(Entity.ACTIVE);
                orderReceivingParties.add(receiver);
            }
            for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                orderReceivingParty.setJcOrderId(jcOrder.getId());
                if (orderReceivingParty.getType() == 1) {
                    addressType = orderReceivingParty.getAddressType();
                    jcOrderHandleService.handyRp(orderReceivingParty, jcOrder.getJcToOrganizationId(), jcOrder.getJcCustomerId(), jcOrder.getJcEndZoneId()); //处理收货方方便利性
                } else {
                    jcOrderHandleService.handyRp(orderReceivingParty, jcOrder.getJcFromOrganizationId(), jcOrder.getJcCustomerId(), jcOrder.getJcStartZoneId());
                }
                orderReceivingParty.setCreateName(SecurityUtils.getUsername());
                orderReceivingParty.setCreateTime(DateUtils.getNowDate());
            }

            jcOrderReceivingPartyService.saveBatch(orderReceivingParties);

            //保存货品明细
            int n = 0; //计算数量
            BigDecimal w = BigDecimal.ZERO; //计算重量
            BigDecimal t = BigDecimal.ZERO; //计算体积
            BigDecimal v = BigDecimal.ZERO; //计算货值
            BigDecimal j = BigDecimal.ZERO; //计算计重

            List<JcOrderProduct> orderProducts = jcOrder.getOrderProducts(); //获取货品信息
            for (JcOrderProduct orderProduct : orderProducts) {
                n += orderProduct.getNumber();
                t = t.add(orderProduct.getVolume() == null ? BigDecimal.ZERO : orderProduct.getVolume());
                w = w.add(orderProduct.getWeight() == null ? BigDecimal.ZERO : orderProduct.getWeight());
                v = v.add(orderProduct.getValue() == null ? BigDecimal.ZERO : orderProduct.getValue());
                j = j.add(orderProduct.getJzWeight() == null ? BigDecimal.ZERO : orderProduct.getJzWeight());
                orderProduct.setJcOrderId(jcOrder.getId());
                orderProduct.setCreateTime(DateUtils.getNowDate());
                orderProduct.setCreateName(SecurityUtils.getUsername());
                orderProduct.setStatus(Entity.ACTIVE);
            }
            jcOrderProductService.saveBatch(orderProducts);
            // 更新金额、体积等数据
            jcOrder.setNumber(n);
            jcOrder.setWeight(w);
            jcOrder.setVolume(t);
            jcOrder.setValue(v);
            jcOrder.setJzWeight(j);
            jcOrder.setHxType(0);//核销状态，0未核销
            jcOrderMapper.updateById(jcOrder);
            jcOrderHandleService.handleOrderBarcode(jcOrder, orderProducts);
            jcOrderHandleService.handleAddLedgerDetail(jcOrder, addressType);
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return 0;
    }


    /**
     * 新增订单
     *
     * @param jcOrder 订单
     * @return 结果
     */
    @Override
    public int insertJcOrder(JcOrder jcOrder) {
        return SpringUtils.getBean(this.getClass()).saveOrder(jcOrder);
    }

    @Override
    public int recheckOrder(JcOrderRecheckVO recheckVO) {
        if (recheckVO.getRecheckTime() == null) {
            recheckVO.setRecheckTime(new Date());
        }
        List<JcOrder> jcOrders = listByIds(Arrays.asList(recheckVO.getIds()));
        List<JcOrder>  newJcOrders = new ArrayList<>();
        for (JcOrder jcOrder : jcOrders) {
            if (jcOrder.getStatus() == 1 && jcOrder.getRecheckStatus() == YesOrNo.N) {
                jcOrder.setRecheckStatus(YesOrNo.Y);
                jcOrder.setRecheckTime(new Date());
                jcOrder.setRecheckUserId(recheckVO.getRecheckUserId());
                newJcOrders.add(jcOrder);
            }
        }
        if (newJcOrders.isEmpty()) {
            throw new ServiceException("订单状态异常，不能重复审核");
        }
        return jcOrderMapper.updateBatch(newJcOrders,
                new UpdateBatchWrapper<JcOrder>().setUpdateFields(
                        JcOrder::getRecheckStatus,
                        JcOrder::getRecheckTime,
                        JcOrder::getRecheckUserId
                )
        );
    }

    /**
     * 新增订单
     *
     * @param jcOrder 订单
     * @return 结果
     */
    public int handelImportJcOrder(JcOrder jcOrder, JcOrderImportVo importVo, JcSysOrganization organization) {
        //绑定组织机构(通过客户所属机构来判断)
        JcCustomer customer = jcCustomerService.selectJcCustomerById(jcOrder.getJcCustomerId());
        if (StringUtils.isEmpty(jcOrder.getCustomerName()) && customer != null) {
            jcOrder.setCustomerName(customer.getName());
        }
        jcOrder.setCode(redisCodeUtil.getOrderCode());
        jcOrder.setJcOrganizationId(SecurityUtils.getOrgId());
        jcOrder.setIsTake(0);
        if (jcOrder.getIsBack() == 0) {
            //处理回单份数
            jcOrder.setBackNumber(0);
        }
        //处理合同是否超期
        if (jcOrder.getCustomer() == null) {
            jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
        } else {
            if (customer.getDays() > 0) {
                jcOrder.setCustomerIsExceed(Entity.ACTIVE);
            } else {
                jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
            }
        }
        //增加路由信息
        BhTimeLiness timeList = jcTimeLinessService.selectJcTimeLinessByOrgs(jcOrder.getJcOrganizationId(), jcOrder.getJcToOrganizationId());
        if (timeList != null) {
            jcOrder.setRouterOrgIds(timeList.getRouterOrgIds());
        } else {
            jcOrder.setRouterOrgIds(jcOrder.getJcOrganizationId() + "," + jcOrder.getJcToOrganizationId());
        }
        //增加路由信息
        jcOrder.setStatus(OrderStatus.ACTIVE.getValue());
        jcOrder.setCreateName(SecurityUtils.getUsername());
        jcOrder.setCreateTime(DateUtils.getNowDate());
        int num = jcOrderMapper.insert(jcOrder); //保存订单单头
        //保存货品明细
        int n = 0; //计算数量
        BigDecimal w = BigDecimal.ZERO; //计算重量
        BigDecimal t = BigDecimal.ZERO; //计算体积
        BigDecimal v = BigDecimal.ZERO; //计算货值
        BigDecimal j = BigDecimal.ZERO; //计算计重

        List<JcOrderProduct> orderProducts = jcOrder.getOrderProducts(); //获取货品信息
        for (JcOrderProduct orderProduct : orderProducts) {
            n += orderProduct.getNumber();
            t = t.add(orderProduct.getVolume() == null ? BigDecimal.ZERO : orderProduct.getVolume());
            w = w.add(orderProduct.getWeight() == null ? BigDecimal.ZERO : orderProduct.getWeight());
            v = v.add(orderProduct.getValue() == null ? BigDecimal.ZERO : orderProduct.getValue());
            j = j.add(orderProduct.getJzWeight() == null ? BigDecimal.ZERO : orderProduct.getJzWeight());
            orderProduct.setJcOrderId(jcOrder.getId());
            orderProduct.setCreateTime(DateUtils.getNowDate());
            orderProduct.setCreateName(SecurityUtils.getUsername());
            orderProduct.setStatus(Entity.ACTIVE);
        }
        jcOrderProductService.saveBatch(orderProducts);
        // 更新金额、体积等数据
        jcOrder.setNumber(n);
        jcOrder.setWeight(w);
        jcOrder.setVolume(t);
        jcOrder.setValue(v);
        jcOrder.setJzWeight(j);
        jcOrder.setHxType(0);//核销状态，0未核销

        jcOrderMapper.updateById(jcOrder);

        jcOrderHandleService.handleOrderBarcode(jcOrder, orderProducts);
        jcOrderHandleService.handleAddLedgerDetail(jcOrder, importVo.getToAddressType());
        jcOrderHandleService.handleFromAndToAddress(importVo, organization, jcOrder);
        return num;
    }

    /**
     * 新修改确认订单，需要将原来老的修改为新的，速度会加快
     *
     * @param ids 订单
     * @return
     */
    @Override
    public int confirmOrderSave(String[] ids) {
        List<JcOrder> jcOrders = listByIds(Arrays.asList(ids));
        List<JcVerificationZb> verificationZbs = new ArrayList<>();
        List<JcInOrOutRecord> inOrOutRecords = new ArrayList<>();
        List<JcOrderBack> orderBacks = new ArrayList<>();
        List<JcLed> leds = new ArrayList<>();
        for (JcOrder order : jcOrders) {
            // 需要核查通过才能确认
            if(order.getRecheckStatus() == YesOrNo.N) {
                throw new ServiceException(order.getCode() + "的订单未核查通过，不能确认");
            }
            SpringUtils.getBean(this.getClass()).handleJcOrder(order);
            // 零散客户必须存在收费
            if (order.getCustomerType() == 0) {
                List<JcLedgerDetail> orderLedgerDetails = jcLedgerDetailService.selectJcLedgerDetailListByOrderId(order.getId());
                if (orderLedgerDetails == null || orderLedgerDetails.isEmpty()) {
                    throw new ServiceException(order.getCode() + "的订单零散客户必须存在收费项目才能确认！");
                }
                order.setLedgerDetails(orderLedgerDetails);
            }
            if (StringUtils.isBlank(order.getRouterOrgIds())) {
                throw new ServiceException("订单路由不能为空，请在服务区域->干线费用时效中添加路由线路和时效并重新保存！！！");
            }
            if (order.getStatus() != 1) {
                throw new ServiceException(order.getCode() + "只能确认保存状态下的订单");
            }
            if (order.getJcCustomerId() != null && order.getCustomerType() == 1) {
                if (order.getFromOrganization().getIsOverdueContract() == 0) {
                    Date startTime = order.getCustomer().getStartTime();
                    Date endTime = order.getCustomer().getEndTime();
                    Date timestamp = new Date();
                    boolean b = DateUtils.belongCalendar(timestamp, startTime, endTime);
                    if (!b) {
                        throw new ServiceException(order.getCode() + "合同超期不能确认");
                    }
                }
            }
            jcOrderTrackService.addTrack(order.getId(), "您的订单在已被受理,正在等待装车 操作人:" + SecurityUtils.getUsername());
            order.setStatus(OrderStatus.CONFIGRM.getValue());// 修改订单状态
            order.setModifyName(SecurityUtils.getUsername());
            order.setModifyTime(DateUtils.getNowDate());

            //--------------------------end---------------------
            JcLed led = jcLedConvert.toLed(order);

            //处理单头
            led.setJcOrderId(order.getId());
            led.setOrderCode(order.getCode());
            led.setCode(led.getCode() + CODE_ONE);
            led.setJcFormOrganizationId(order.getJcFromOrganizationId());
            led.setStatus(OrderStatus.CONFIGRM.getValue());
            if (order.getOrderReceivingParties() != null && order.getOrderReceivingParties().size() > 0) {
                List<JcLedReceivingParty> ledReceivingParties = jcLedReceivingPartyConvert.toDOList(order.getOrderReceivingParties());
                led.setLedReceivingParties(ledReceivingParties);
            }

            /**
             * 数量
             */
            Integer number = null;
            BigDecimal volume = null;
            BigDecimal weight = null;

            if (order.getOrderProducts() != null && order.getOrderProducts().size() > 0) {
                List<JcLedProduct> ledProducts = jcLedProductConvert.toDOList(order.getOrderProducts());
                number = ledProducts.stream().filter(w -> w.getNumber() != null).mapToInt(JcLedProduct::getNumber).sum();
                volume = ledProducts.stream().map(JcLedProduct::getVolume).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                weight = ledProducts.stream().map(JcLedProduct::getWeight).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                led.setLedProducts(ledProducts);
            }
            led.setCreateName(SecurityUtils.getUsername());
            led.setCreateTime(DateUtils.getNowDate());
            //存储分段单据
            led.setId(null);
            jcLedService.save(led);
            leds.add(led);

            JcInOrOutRecord inOrOutRecord = new JcInOrOutRecord();
            inOrOutRecord.setNumber(number);
            inOrOutRecord.setVolume(volume);
            inOrOutRecord.setWeight(weight);
            inOrOutRecord.setJcLedId(led.getId());
            inOrOutRecord.setJcOrganizationId(order.getJcFromOrganizationId());
            inOrOutRecord.setTime(new Date());
            inOrOutRecord.setType(0);
            inOrOutRecord.setJcZoneStoreroomId(order.getJcZoneStoreroomId());
            inOrOutRecord.setCreateName(SecurityUtils.getUsername());
            inOrOutRecord.setCreateTime(DateUtils.getNowDate());
            inOrOutRecords.add(inOrOutRecord);

            //处理回单
            if (order.getIsBack() == 1) {
                JcOrderBack orderBack = new JcOrderBack();
                orderBack.setJcOrderId(order.getId());
                orderBack.setJcOrganizationId(order.getJcOrganizationId());
                orderBack.setSingNumber(0);
                orderBack.setBackNumber(order.getBackNumber());
                orderBack.setCreateName(SecurityUtils.getUsername());
                orderBack.setCreateTime(DateUtils.getNowDate());
                orderBacks.add(orderBack);
            }
            List<JcLedgerDetail> ledgerDetails = order.getLedgerDetails();
            if (ledgerDetails != null && !ledgerDetails.isEmpty()) {
                BigDecimal amount = BigDecimal.ZERO;
                BigDecimal input = BigDecimal.ZERO;
                for (JcLedgerDetail ledgerDetail : ledgerDetails) {
                    amount = amount.add(ledgerDetail.getAmount());
                    input = input.add(ledgerDetail.getInput());
                }
                //订单确认后，向核销表插入一条数据
                JcVerificationZb verificationZb = new JcVerificationZb();
                verificationZb.setJcOrganizationId(SecurityUtils.getOrgId());
                verificationZb.setJcOrderId(order.getId());
                verificationZb.setStatus(VerifiZbStatus.UNACTIVE);
                verificationZb.setHxStatus(0);
                verificationZb.setWhxMoney(amount);
                verificationZb.setZmoney(amount);
                verificationZb.setZinput(input);
                verificationZb.setHxCount(0);
                verificationZb.setType(0);
                verificationZb.setHxMoney(BigDecimal.ZERO);
                verificationZb.setTzSource(0L);
                verificationZb.setCreateName(SecurityUtils.getUsername());
                verificationZb.setCreateTime(DateUtils.getNowDate());
                verificationZbs.add(verificationZb);
            }
        }
        if (!verificationZbs.isEmpty()) {
            jcVerificationZbService.saveBatch(verificationZbs);
        }
        jcInOrOutRecordService.saveBatch(inOrOutRecords);
        if (!orderBacks.isEmpty()) {
            jcOrderBackService.saveBatch(orderBacks);
        }
        // 处理分段订单数据
        jcLedService.handleJcLedInsert(leds);
        SpringUtils.getBean(this.getClass()).updateBatchById(jcOrders);
        return leds.size();
    }

    /**
     * 修改订单
     *
     * @param jcOrder 订单
     * @return 结果
     */
    @Override
    public int updateJcOrder(JcOrder jcOrder) {
        jcOrder.setModifyName(SecurityUtils.getUsername());
        jcOrder.setModifyTime(DateUtils.getNowDate());

        //绑定组织机构(通过客户所属机构来判断)
        SysUser user = SecurityUtils.getSysUser();
        Long jcOrganizationId;
        JcCustomer customer = jcCustomerService.selectJcCustomerById(jcOrder.getJcCustomerId());
        if (StringUtils.isEmpty(jcOrder.getCustomerName()) && customer != null) {
            jcOrder.setCustomerName(customer.getName());
        }
        if (Objects.equals(user.getUserType(), UserConstants.SYSTEM_USER_TYPE)) {
            jcOrganizationId = SecurityUtils.getOrgId();
        } else {
            jcOrganizationId = customer.getJcOrganizationId();
            // 客户(查询所属组织)
//            organization = jcSysOrganizationService.selectJcSysOrganizationById(customer.getJcOrganizationId());
            // 获取 user
//            List<JcSysUserOrganization> userOrganizations = jcSysUserOrganizationService.selectJcSysUserOrganizationByOrgId(customer.getJcOrganizationId());
//            if (userOrganizations.size() > 0) {
//                JcSysUserOrganization userOrganization = userOrganizations.get(0);
//                // 最好根据角色来判断 --TODO
//                user = sysUserService.selectUserById(Long.parseLong(userOrganization.getUserId()));
//            }
        }
        if (jcOrder.getIsBack() == 0) {
            //处理回单份数
            jcOrder.setBackNumber(0);
        }

        jcOrder.setIsTake(0);
        //处理合同是否超期
        if (jcOrder.getCustomer() == null) {
            jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
        } else {
            if (customer.getDays() > 0) {
                jcOrder.setCustomerIsExceed(Entity.ACTIVE);
            } else {
                jcOrder.setCustomerIsExceed(Entity.UNACTIVE);
            }
        }
        //增加路由信息
        BhTimeLiness timeList = jcTimeLinessService.selectJcTimeLinessByOrgs(jcOrder.getJcOrganizationId(), jcOrder.getJcToOrganizationId());
        if (timeList != null) {
            jcOrder.setRouterOrgIds(timeList.getRouterOrgIds());
        } else {
            throw new ServiceException("路线信息不存在，请先添加路线！");
        }
        try {
            //增加路由信息
            int num = jcOrderMapper.updateById(jcOrder); //保存订单单头
            //保存收发货方
            String addressType = "";
            List<JcOrderReceivingParty> orderReceivingParties = jcOrder.getOrderReceivingParties();//获取收发货方
            if (orderReceivingParties == null || orderReceivingParties.size() == 0) {
                // 两种方式
                orderReceivingParties = new ArrayList<>();
                orderReceivingParties.add(jcOrder.getSender());
                orderReceivingParties.add(jcOrder.getReceiver());
            }
            for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                orderReceivingParty.setJcOrderId(jcOrder.getId());
                if (orderReceivingParty.getType() == 1) {
                    jcOrderHandleService.handyRp(orderReceivingParty, jcOrder.getJcToOrganizationId(), jcOrder.getJcCustomerId(), jcOrder.getJcEndZoneId()); //处理收货方方便利性
                    addressType = orderReceivingParty.getAddressType();
                } else if (orderReceivingParty.getType() == 0) {
                    jcOrderHandleService.handyRp(orderReceivingParty, jcOrder.getJcOrganizationId(), jcOrder.getJcCustomerId(), jcOrder.getJcStartZoneId()); //处理
                }
                orderReceivingParty.setCreateName(SecurityUtils.getUsername());
                orderReceivingParty.setCreateTime(DateUtils.getNowDate());
            }
            jcOrderReceivingPartyService.updateBatchById(orderReceivingParties);

            //保存货品明细
            int n = 0; //计算数量
            BigDecimal w = BigDecimal.ZERO; //计算重量
            BigDecimal t = BigDecimal.ZERO; //计算体积
            BigDecimal v = BigDecimal.ZERO; //计算货值
            BigDecimal j = BigDecimal.ZERO; //计算计重

            List<JcOrderProduct> orderProducts = jcOrder.getOrderProducts(); //获取货品信息
            for (JcOrderProduct orderProduct : orderProducts) {
                n += orderProduct.getNumber();
                t = t.add(orderProduct.getVolume() == null ? BigDecimal.ZERO : orderProduct.getVolume());
                w = w.add(orderProduct.getWeight() == null ? BigDecimal.ZERO : orderProduct.getWeight());
                v = v.add(orderProduct.getValue() == null ? BigDecimal.ZERO : orderProduct.getValue());
                j = j.add(orderProduct.getJzWeight() == null ? BigDecimal.ZERO : orderProduct.getJzWeight());
                orderProduct.setJcOrderId(jcOrder.getId());
                orderProduct.setCreateTime(DateUtils.getNowDate());
                orderProduct.setCreateName(SecurityUtils.getUsername());
                orderProduct.setStatus(Entity.ACTIVE);
            }
            // 先删除
            jcOrderBarcodeMapper.deleteByOrderIds(List.of(jcOrder.getId()));
            jcOrderProductMapper.deleteByOrderIds(List.of(jcOrder.getId()));
            jcOrderProductService.saveBatch(orderProducts);
            // 更新金额、体积等数据
            jcOrder.setNumber(n);
            jcOrder.setWeight(w);
            jcOrder.setVolume(t);
            jcOrder.setValue(v);
            jcOrder.setJzWeight(j);
            jcOrder.setHxType(0);//核销状态，0未核销
            jcOrderMapper.updateById(jcOrder);
            jcOrderHandleService.handleOrderBarcode(jcOrder, orderProducts);
            jcOrderHandleService.handleAddLedgerDetail(jcOrder, addressType);
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int saveAbnormalJcOrder(JcOrder updateOrder, String reason) {
        JcOrder oldOrder = this.selectJcOrderById(updateOrder.getId());
        JcAbnormal abnormal = new JcAbnormal();
        abnormal.setJcOrganizationId(SecurityUtils.getOrgId());
        // 获取一次字段信息，并保存异常信息
        List<JcAbnormalDetail> abnormalList = jcAbnormalDetailService.getAbnormalList(oldOrder, updateOrder);
        //处理合同是否超期
        if (oldOrder.getCustomer() == null) {
            oldOrder.setCustomerIsExceed(Entity.UNACTIVE);
        } else {
            JcCustomer customer = jcCustomerService.selectJcCustomerById(oldOrder.getJcCustomerId());
            Date startTime = customer.getStartTime();
            Date endTime = customer.getEndTime();
            Date timestamp = oldOrder.getTime();
            boolean b = DateUtils.belongCalendar(timestamp, startTime, endTime);
            if (b) {
                oldOrder.setCustomerIsExceed(Entity.UNACTIVE);
            } else {
                oldOrder.setCustomerIsExceed(Entity.ACTIVE);
            }
        }
        if (oldOrder.getIsBack() == 1) {
            List<JcOrderBack> list = jcOrderBackService.selectJcOrderBackListByOrderId(oldOrder.getId());
            if (list.size() < 1) {
                JcOrderBack orderBack = new JcOrderBack();
                orderBack.setJcOrderId(oldOrder.getId());
                orderBack.setSingNumber(0);
                orderBack.setBackNumber(oldOrder.getBackNumber());
                jcOrderBackService.save(orderBack);
            }
        }
        List<JcVerificationZb> verifications = verificationZbService.selectJcVerificationZbByJcOrderId(oldOrder.getId());//核销总表
        List<JcOrderReceivingParty> orderReceivingParties = oldOrder.getOrderReceivingParties();//获取收发货方
        List<JcOrderReceivingParty> orderReceivingParties1 = updateOrder.getOrderReceivingParties();
        for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
            for (JcOrderReceivingParty orderReceivingParty1 : orderReceivingParties1) {
                if (orderReceivingParty1.getId().equals(orderReceivingParty.getId())) {
                    String type = null;
                    if (orderReceivingParty.getType() == 0) {
                        //如果是发货方
                        type = "发货方";
                    } else {
                        type = "收货方";
                    }
                    if (!orderReceivingParty.getName().equals(orderReceivingParty1.getName())) {
                        abnormalList.add(getAbnormalDetail(type + "客户名称", orderReceivingParty.getName(), "name", orderReceivingParty1.getName()));
                        orderReceivingParty.setName(orderReceivingParty1.getName());
                    }
                    if (!orderReceivingParty.getContactperson().equals(orderReceivingParty1.getContactperson())) {
                        abnormalList.add(getAbnormalDetail(type + "联系人", orderReceivingParty.getContactperson(), "contactperson", orderReceivingParty1.getContactperson()));
                        orderReceivingParty.setContactperson(orderReceivingParty1.getContactperson());
                    }
                    if (!orderReceivingParty.getIphone().equals(orderReceivingParty1.getIphone())) {
                        abnormalList.add(getAbnormalDetail(type + "电话", orderReceivingParty.getIphone(), "iphone", orderReceivingParty1.getIphone()));
                        orderReceivingParty.setIphone(orderReceivingParty1.getIphone());
                    }
                    if (!orderReceivingParty.getAddress().equals(orderReceivingParty1.getAddress())) {
                        abnormalList.add(getAbnormalDetail(type + "地址", orderReceivingParty.getAddress(), "address", orderReceivingParty1.getAddress()));
                        orderReceivingParty.setAddress(orderReceivingParty1.getAddress());
                    }
                    if (!orderReceivingParty.getAddress().equals(orderReceivingParty1.getDetaileAddress())) {
                        abnormalList.add(getAbnormalDetail(type + "详细地址", orderReceivingParty.getDetaileAddress(), "detailedAddress", orderReceivingParty1.getDetaileAddress()));
                        orderReceivingParty.setAddress(orderReceivingParty1.getDetaileAddress());
                    }
                    if (!orderReceivingParty.getLtl().equals(orderReceivingParty1.getLtl())) {
                        abnormalList.add(getAbnormalDetail(type + "经纬度", orderReceivingParty.getLtl(), "ltl", orderReceivingParty1.getLtl()));
                        orderReceivingParty.setLtl(orderReceivingParty1.getLtl());
                    }
                }
            }
        }
        List<JcOrderProduct> orderProducts = oldOrder.getOrderProducts();
        List<JcOrderProduct> orderProducts1 = updateOrder.getOrderProducts();
        if (orderProducts.size() != orderProducts1.size()) {
            throw new MessageException("不能修改货品明细数量");
        }
        for (JcOrderProduct orderProduct : orderProducts) {
            for (JcOrderProduct orderProduct1 : orderProducts1) {
                if (orderProduct1.getId().equals(orderProduct.getId())) {
                    if (!orderProduct.getName().equals(orderProduct1.getName())) {
                        abnormalList.add(getAbnormalDetail("货品名称", orderProduct.getName(), "name", orderProduct1.getName()));
                        orderProduct.setName(orderProduct1.getName());
                    }
                    if (StringUtils.isNotBlank(orderProduct.getDescription()) && !orderProduct.getDescription().equals(orderProduct1.getDescription())) {
                        abnormalList.add(getAbnormalDetail("备注", orderProduct.getDescription(), "name", orderProduct1.getDescription()));
                        orderProduct.setDescription(orderProduct1.getDescription());
                    }
                    if (orderProduct.getUnit() != null && orderProduct1.getUnit() != null && !orderProduct.getUnit().equals(orderProduct1.getUnit())) {
                        abnormalList.add(getAbnormalDetail("货品-" + orderProduct.getName() + "-单位", orderProduct.getUnit(), "unit", orderProduct1.getUnit()));
                        orderProduct.setUnit(orderProduct1.getUnit());
                    }
                    BigDecimal weight = orderProduct.getWeight();
                    BigDecimal weight1 = orderProduct1.getWeight();
                    if (!weight.equals(weight1)) {
                        abnormalList.add(getAbnormalDetail("货品-" + orderProduct.getName() + "-重量", String.valueOf(orderProduct.getWeight()), "weight", String.valueOf(orderProduct1.getWeight())));
                        orderProduct.setWeight(orderProduct1.getWeight());
                    }
                    int number = orderProduct.getNumber();
                    int number1 = orderProduct1.getNumber();
                    if (number != number1) {
                        abnormalList.add(getAbnormalDetail("货品-" + orderProduct.getName() + "-数量", String.valueOf(orderProduct.getNumber()), "number", String.valueOf(orderProduct1.getNumber())));
                        orderProduct.setNumber(orderProduct1.getNumber());
                    }
                    BigDecimal volume1 = orderProduct.getVolume();
                    BigDecimal volume = orderProduct1.getVolume();
                    if (!volume1.equals(volume)) {
                        abnormalList.add(getAbnormalDetail("货品-" + orderProduct.getName() + "-体积", String.valueOf(orderProduct.getVolume()), "volume", String.valueOf(orderProduct1.getVolume())));
                        orderProduct.setVolume(orderProduct1.getVolume());
                    }
                    BigDecimal value = orderProduct.getValue();
                    BigDecimal value1 = orderProduct1.getValue();
                    if (!Objects.equals(value, value1)) {
                        abnormalList.add(getAbnormalDetail("货品-" + orderProduct.getName() + "-货值", String.valueOf(orderProduct.getValue()), "weight", String.valueOf(orderProduct1.getValue())));
                        orderProduct.setValue(orderProduct1.getValue());
                    }
                }

            }
        }
        //费用明细明细
        List<JcLedgerDetail> ledgerDetails = updateOrder.getLedgerDetails();

        for (JcLedgerDetail ledgerDetail : ledgerDetails) {
            if (StringUtils.isEmpty(ledgerDetail.getId())) {
                JcFeeType feeType = jcFeeTypeService.selectJcFeeTypeById(ledgerDetail.getJcFeeTypeId());
                abnormalList.add(getAbnormalDetail("调整费用-" + feeType.getName(), "0", "调整费用-" + feeType.getName() + "  税率:" + ledgerDetail.getTaxrate(), ledgerDetail.getAmount().toString()));
                ledgerDetail.setJcOrderId(oldOrder.getId());
                ledgerDetail.setCategory(1);
                ledgerDetail.setType(0);
                JcVerificationZb verificationZb = verifications.get(0);
                verificationZb.setWhxMoney(verificationZb.getWhxMoney().add(ledgerDetail.getAmount()));
                verificationZb.setZmoney(verificationZb.getZmoney().add(ledgerDetail.getAmount()));
                if (verificationZb.getStatus() == VerifiZbStatus.ACTIVE) {//核销完毕
                    verificationZb.setStatus(VerifiZbStatus.PART_VER);//变成部分核销
                }
                jcLedgerDetailService.save(ledgerDetail);
            }
        }


        List<JcOrderProduct> newOrderP = oldOrder.getOrderProducts();


        int n = 0; //计算数量
        BigDecimal w = BigDecimal.ZERO; //计算重量
        BigDecimal t = BigDecimal.ZERO; //计算体积
        BigDecimal v = BigDecimal.ZERO; //计算货值
        for (JcOrderProduct orderProduct : newOrderP) {
            n += orderProduct.getNumber();
            t = t.add(orderProduct.getVolume());
            w = w.add(orderProduct.getWeight());
            v = v.add(orderProduct.getValue());
            orderProduct.setJcOrderId(oldOrder.getId());
        }
        oldOrder.setNumber(n);
        oldOrder.setWeight(w);
        oldOrder.setVolume(t);
        oldOrder.setValue(v);
        oldOrder.setIsAbnormal(1);
        abnormal.setNumber(abnormalList.size());
        abnormal.setDescription(reason);
        abnormal.setJcOrderId(oldOrder.getId());
        abnormal.setTime(DateUtils.getNowDate());
        abnormal.setType(0);
        jcAbnormalService.save(abnormal);
        if (abnormalList.size() == 0) {
            throw new MessageException("没有异常，不用修改");
        }
        for (JcAbnormalDetail abnormalDetail : abnormalList) {
            abnormalDetail.setJcAbnormalId(abnormal.getId());
            jcAbnormalDetailService.save(abnormalDetail);
        }
        return jcOrderMapper.updateById(oldOrder);
    }

    @Override
    public int copyOrders(Long[] ids, String operName) {
        //获取原始数据
        List<JcOrder> jcOrders = jcOrderMapper.selectBatchIds(Arrays.asList(ids));
        for (JcOrder order : jcOrders) {
            //去掉ID
            JcOrder newOrder = new JcOrder();
            BeanUtils.copyProperties(order, newOrder);
            newOrder.setId(null);
            //订单号
            newOrder.setCode(redisCodeUtil.getOrderCode());
            //订单日期
            Date date = new Date();
            Date timestamp = new Timestamp(date.getTime());
            newOrder.setTime(timestamp);
            //创建日期
            newOrder.setCreateTime(timestamp);
            //创建人
            newOrder.setCreateName(operName);
            //修改事件修改人为空
            newOrder.setModifyTime(null);
            newOrder.setModifyName(null);
            newOrder.setStatus(OrderStatus.ACTIVE.getValue());
            //保存订单
            this.save(newOrder);

            //保存收发货方
            List<JcOrderReceivingParty> orderReceivingParties = jcOrderReceivingPartyService.selectJcOrderReceivingpartyListByOrderId(order.getId());
            //获取收发货方service
            List<JcOrderReceivingParty> newOrderReceivingPartys = new ArrayList<>();
            for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                JcOrderReceivingParty newOrderReceivingParty = new JcOrderReceivingParty();
                BeanUtils.copyProperties(orderReceivingParty, newOrderReceivingParty);
                newOrderReceivingParty.setId(null);
                newOrderReceivingParty.setCreateTime(timestamp);
                newOrderReceivingParty.setCreateName(SecurityUtils.getUsername());
                newOrderReceivingParty.setJcOrderId(newOrder.getId());
                newOrderReceivingPartys.add(newOrderReceivingParty);
            }
            jcOrderReceivingPartyService.saveBatch(newOrderReceivingPartys);

            //保存货品明细
            List<JcOrderProduct> orderProducts = jcOrderProductService.selectJcOrderProductListByOrderId(order.getId());
            List<JcOrderProduct> newOrderProducts = new ArrayList<>();
            //货品明细Dao
            for (JcOrderProduct orderProduct : orderProducts) {
                JcOrderProduct newOrderProduct = new JcOrderProduct();
                BeanUtils.copyProperties(orderProduct, newOrderProduct);
                newOrderProduct.setId(null);
                newOrderProduct.setCreateTime(timestamp);
                newOrderProduct.setCreateName(SecurityUtils.getUsername());
                //handyRp(orderReceivingParty1);
                newOrderProduct.setJcOrderId(newOrder.getId());
                newOrderProducts.add(newOrderProduct);
            }
            jcOrderProductService.saveBatch(newOrderProducts);

            //获取台账
            List<JcLedgerDetail> ledgerDetails = jcLedgerDetailService.selectJcLedgerDetailListByOrderId(order.getId());
            List<JcLedgerDetail> newLedgerDetails = new ArrayList<>();
            //台账明细Dao
            for (JcLedgerDetail ledgerDetail : ledgerDetails) {
                JcLedgerDetail newLedgerDetail = new JcLedgerDetail();
                BeanUtils.copyProperties(ledgerDetail, newLedgerDetail);
                newLedgerDetail.setId(null);
                newLedgerDetail.setCreateTime(timestamp);
                newLedgerDetail.setCreateName(SecurityUtils.getUsername());
                newLedgerDetail.setJcOrderId(newOrder.getId());
                ledgerDetail.setStatus(Entity.ACTIVE);
                ledgerDetail.setIsConfirm(0);
                newLedgerDetails.add(newLedgerDetail);
            }
            jcLedgerDetailService.saveBatch(newLedgerDetails);
        }
        return 1;

    }

    private JcAbnormalDetail getAbnormalDetail(String source, String sourceValue, String targer, String targetValue) {
        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
        abnormalDetail.setSource(source);
        abnormalDetail.setTarger(targer);
        abnormalDetail.setSourceValue(sourceValue);
        abnormalDetail.setTargerValue(targetValue);
        return abnormalDetail;
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteJcOrderByIds(Long[] ids) {
        List<JcOrder> jcOrders = jcOrderMapper.selectBatchIds(Arrays.asList(ids));
        if (jcOrders.size() != 0) {
            for (JcOrder jcOrder : jcOrders) {
                // 判断状态
                if (jcOrder.getStatus() != OrderStatus.ACTIVE.getValue()) {
                    throw new MessageException("订单状态不正确，不能删除");
                }
            }
        }
        // 删除几个关联内容
        jcOrderBarcodeMapper.deleteByOrderIds(List.of(ids));
        jcOrderReceivingpartyMapper.deleteByOrderIds(List.of(ids));
        jcOrderTrackMapper.deleteByOrderIds(List.of(ids));
        jcOrderProductMapper.deleteByOrderIds(List.of(ids));
        jcLedgerDetailMapper.deleteByOrderIds(List.of(ids));
        return jcOrderMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteJcOrderById(Long id) {
        return jcOrderMapper.deleteById(id);
    }

    @Override
    public int deleteSysJcOrderByIds(String[] ids) {
        List<Long> orderIds;
        List<JcOrder> jcOrders = jcOrderMapper.selectBatchIds(Arrays.asList(ids));
        if (jcOrders == null || jcOrders.isEmpty()) {
            jcOrders = jcOrderMapper.selectJcOrderListByCodes(List.of(ids));
        }
        orderIds = jcOrders.stream().map(JcOrder::getId).toList();

        if (!jcOrders.isEmpty()) {
            for (JcOrder jcOrder : jcOrders) {
                // 判断状态
                if (jcOrder.getStatus() >= OrderStatus.DESPATCH.getValue()) {
                    throw new MessageException("订单状态已经为发运，不能删除");
                }
            }
        }
        // 删除ORDER关联内容
        jcOrderBarcodeMapper.deleteByOrderIds(orderIds);
        jcOrderReceivingpartyMapper.deleteByOrderIds(orderIds);
        jcOrderTrackMapper.deleteByOrderIds(orderIds);
        jcOrderProductMapper.deleteByOrderIds(orderIds);
        jcLedgerDetailMapper.deleteByOrderIds(orderIds);

        // 删除LED jc_led_product jc_led_receivingparty jc_inoroutrecord  jc_led
//        for (Long orderId : orderIds) {
//            List<JcLed> leds = jcLedService.selectDeliverJcLedsByOrderId(orderId);
//            if (leds != null && !leds.isEmpty()) {
//                List<Long> ledIds = leds.stream().map(JcLed::getId).toList();
//                jcLedProductService.deleteJcLedProductByLedIds(ledIds);
//                jcLedReceivingpartyService.deleteJcLedReceivingpartyByLedIds(ledIds);
//                jcInOrOutRecordService.de(ledIds);
//                jcLedService.removeBatchByIds(ledIds);
//            }
//        }

        return jcOrderMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
